<?php
/**
 * Created by PhpStorm.
 * User: thorjiang
 * Date: 2018/5/9
 * Time: 19:10
 */

namespace App\Repositories;

use App\Models\TicketModel;
use InfyOm\Generator\Common\BaseRepository;

/**
 * Class UserModelRepository
 * @package App\Repositories
 * @version May 9, 2018, 8:43 am UTC
 *
 * @method TicketModel findWithoutFail($id, $columns = ['*'])
 * @method TicketModel find($id, $columns = ['*'])
 * @method TicketModel first($columns = ['*'])
 */
class TicketModelRepository extends BaseRepository
{
    /**
     * Configure the Model
     **/
    public function model()
    {
        return TicketModel::class;
    }

    /**
     * 验证优惠券是否有效
     * @param $ticket
     */
    public function validateTicket($ticket)
    {
        if (empty($ticket)) {
            throwResponseException(1, '优惠券不存在');
        }

        // 限时优惠券是否能领取
        if ($ticket->type == TicketModel::TYPE_TIME) {
            if (strtotime($ticket->valid_time) < time()) {
                throwResponseException(1, '过期不能领取');
            }
        }

        // 优惠券是否有效
        if ($ticket->status != TicketModel::STATUS_NORMAL) {
            throwResponseException(1, '当前不能领取');
        }

        $start = $ticket->start_time;
        $end = $ticket->end_time;
        if (strtotime($start) > time()) {
            throwResponseException(1, '未到领取时间,当前不能领取');
        } elseif (strtotime($end) < time()) {
            throwResponseException(1, '超出领取时间,不可领取');
        }

        // 优惠券剩余次数
        if ($ticket->left_times <= 0) {
            throwResponseException(1, '优惠券已领完');
        }

    }

    public function search($searchOptions, $sortOptions)
    {
        $qb = (new TicketModel)->getQueryBySearchOptions($searchOptions);

        $count = $qb->count();

        $lists = TicketModel::setPage($qb, $sortOptions);

        $lists['total'] = $count;

        return $lists;
    }
}
